--
-- Author: ping.wang
-- Date: 2018-07-09 15:09:03
--
-- AuctionProductPanel
--
local ListMenu = require("app.widget.ListMenu")
local AuctionFirstTargetRender = import(".renders.AuctionFirstTargetRender")
local AuctionSecondTargetRender = import(".renders.AuctionSecondTargetRender")
local AuctionProductItemRender = import(".renders.AuctionProductItemRender")
local ListViewVertical = require("app.widget.listview.ListViewVertical")

local ClassRef = app.mvc.createPanelClass(...)
local MAX_WORD_LEN = 20
--data =
function ClassRef.createWithData(data, node)
    local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.AuctionProductPanel))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end
function ClassRef.create(node)
    return ClassRef.createWithData(nil, node)
end

--
function ClassRef:init(data)
    self.super.init(self, data)
    self:setContentSize( self._ui.Panel:getContentSize() )

    local tmpText = self._ui.Panel_r:findChild("Panel_tick/text")
    tmpText:setString(L("auction_showFilter1"))

    self._showListType = Enums.AuctionProductType.normal --默认选中普通商品页签

    self._btnGrade = self._ui.Panel_r:findChild("Panel_top/btn_grade") --品质筛选按钮
    self._btnPrice = self._ui.Panel_r:findChild("Panel_top/btn_price") --价格筛选按钮
    self._btnType = self._ui.Panel_r:findChild("Panel_top/btn_type") --类型筛选按钮
    self._gradeNameList = self:_getGradeFilterList(self._btnGrade)
    self._priceNameList = self:_getPriceFilterList(self._btnPrice)
    self._typeNameList = self:_getTypeFilterList(self._btnType,self._showListType)

    self._btnGrade:addClickEventListener(function() self._btnGrade:setBright(false) executeFunc(self._onOperate, "showFilterList",self._gradeNameList) end)
    self._btnPrice:addClickEventListener(function() self._btnPrice:setBright(false) executeFunc(self._onOperate, "showFilterList",self._priceNameList) end)
    self._btnType:addClickEventListener(function() self._btnType:setBright(false) executeFunc(self._onOperate, "showFilterList",self._typeNameList) end)

    self._btnGrade:setPressedActionEnabled(false)
    self._btnPrice:setPressedActionEnabled(false)
    self._btnType:setPressedActionEnabled(false)

    --输入筛选物品名称
    self._btnSearch = self._ui.Panel_r:findChild("Panel_top/Panel_search/Button_enter") --名字筛选按钮
    self._searchTextField = self._ui.Panel_r:findChild("Panel_top/Panel_search/TextField") --筛选文本输入框

    self._ui.Panel_money:setTouchEnabled(true)
    self._ui.Panel_money:addClickEventListener(handler(self, self._showMoneyTips))
    self._moneyNum = self._ui.Panel_money:getChildByName("num") --界面显示自己的金币数量
    self._moneyIcon = self._ui.Panel_money:findChild("icon")

    self._ui.btn_sell:addClickEventListener(function() executeFunc(self._onOperate, "openSalePanel") end)
    self._selectedBtn = self._ui.Panel_r:findChild("Panel_tick/selected_btn") --是否显示符合我等级商品的按钮 是一个checkbox的功能 但是是按钮阿实现
    self._ui.Panel_tick:addClickEventListener(handler(self, self._showMyLvProduct))

    self._preBtn = self._ui.Panel_r:findChild("Panel_page/Button_1")   --上一页按钮
    self._nextBtn = self._ui.Panel_r:findChild("Panel_page/Button_2")   --下一页按钮
    --self._curPageNum = self._ui.Panel_r:findChild("Panel_page/num")     --当前页数显示文字

    self._preBtn:addClickEventListener(function() executeFunc(self._onOperate, "showPrePage") end)  --显示前一页
    self._nextBtn:addClickEventListener(function() executeFunc(self._onOperate, "showNextPage") end) --显示下一页

    self._preBtn:setScale(0.65)
    self._nextBtn:setScale(0.65)
    self._isOnlyShowMyLvProducts = false

    local params = {
        renderClass = AuctionProductItemRender,
        perNum = 1,
        cellEventProxy = function(eventName, data)
            executeFunc(self._onOperate, eventName, data)
        end,
    }

    self._productListnode = ListViewVertical.new( self._ui.Panel_r:findChild("ScrollView"), params )

    self._titleText2 = self._ui.Panel_r:findChild("Panel_tlt/num") --存货 最高出价
    self._titleText3 = self._ui.Panel_r:findChild("Panel_tlt/price") --单价 我的出价

    self:resetSelectFilter()

    --设置搜索输入框
    local function onEditCallback(strEventName,sender)
        local edit = sender
        if strEventName == "changed" then
            local text = edit:getText()
            local ulen = string.ulen(text)
            if ulen > MAX_WORD_LEN then
                local newStr = string.usubstr(text,MAX_WORD_LEN)
                if text~=newStr then
                    edit:setText(newStr)
                    text = newStr
                    display.pushToast(string.format(L("max_input_char"), MAX_WORD_LEN))
                end
            end
        end
    end

    self._editText = display.replaceTextFieldWithEditBox(self._searchTextField)
    self._editText:registerScriptEditBoxHandler(onEditCallback)

    self._btnSearch:addClickEventListener(function() executeFunc(self._onOperate, "searchProductByName",self._editText:getText()) end)
end

--获取品质筛选的列表数据
function ClassRef:_getGradeFilterList(btn)
    local posTemp = btn:convertToWorldSpace(cc.p(0,0))
    local width, height = btn:getContentSize2()
    posTemp.x = posTemp.x + width
    local data = {}
    data.pos = posTemp
    data.dataList = {}
    data.cb = handler(self,self.clickGradeListItem)
    for i = 0, 5 do
        local name = L(string.format("auction_quality%d",i))
        table.insert(data.dataList,{name=name,id=i})
    end

    return data
end

function ClassRef:initMoneyPanel(tabId)
    if tabId == Enums.AuctionProductType.normal then
        local coinId = tonumber(GD:getSystemPar( "auctionNormalGoodsLootType",99))
        local coinConfig = GD:getCoinConfig(coinId)
        local iconPath = string.format("%s%s.png",Res.coinIconPath,coinConfig.icon)
        self._moneyIcon:loadTexture(iconPath)
        self._moneyNum:setString(tostring(UD:getDaibiValue(coinId)))
    else
        local coinId = 99
        local publisher = app:getInnerPublisher()
        if publisher == Enums.Publisher.tencent then
            coinId = tonumber(GD:getSystemPar( "auctionBiddingGoodsLootType_tencent",99))
        else
            coinId = tonumber(GD:getSystemPar( "auctionBiddingGoodsLootType",115))
        end
        local coinConfig = GD:getCoinConfig(coinId)
        local iconPath = string.format("%s%s.png",Res.coinIconPath,coinConfig.icon)
        self._moneyIcon:loadTexture(iconPath)
        self._moneyNum:setString(tostring(UD:getDaibiValue(coinId)))
    end
end

--获取价格筛选列表
function ClassRef:_getPriceFilterList(btn)
    local posTemp = btn:convertToWorldSpace(cc.p(0,0))
    local width, height = btn:getContentSize2()
    posTemp.x = posTemp.x + width
    local data = {}
    data.pos = posTemp
    data.dataList = {}
    data.cb = handler(self,self.clickPriceListItem)
    for i = 1, 2 do
        local name = L(string.format("auction_priceFilter%d",i))
        table.insert(data.dataList,{name=name,id=i})
    end

    return data
end

--获取类型筛选列表
function ClassRef:_getTypeFilterList(btn,productType)
    local posTemp = btn:convertToWorldSpace(cc.p(0,0))
    local width, height = btn:getContentSize2()
    posTemp.x = posTemp.x + width
    local data = {}
    data.pos = posTemp
    data.dataList = {}
    data.cb = handler(self,self.clickTypeListItem)
    local maxnum = 1
    if productType == Enums.AuctionProductType.normal then
        maxnum = 1
    elseif productType == Enums.AuctionProductType.bid then
        maxnum = 2
    end

    for i = 0, maxnum do
        local name = L(string.format("auction_type%d",i))
        table.insert(data.dataList,{name=name,id=i})
    end

    return data
end

--data = {name =v , id = 0}
--选择品质后回调
function ClassRef:clickGradeListItem(data)
    --print(data.name..data.id)
    if cc.isAlive(self) then
        if data.id ~= self._selectedFilterGrade then
            self:_setFilterName(self._btnGrade,data.name)
            self._selectedFilterGrade = data.id
            --所有的操作要在Enums.AuctionFilterType.all 时候生效
            if self._selectedFilterType == Enums.AuctionFilterType.all then
                executeFunc(self._onOperate, "changeFilter")
            end
        end
        self._btnGrade:setBright(true)
    end
end

--选择价格后回调
function ClassRef:clickPriceListItem(data)
    --print(data.name..data.id)
    if cc.isAlive(self) then
        if data.id ~= self._selectedFilterPrice then
            self:_setFilterName(self._btnPrice,data.name)
            self._selectedFilterPrice = data.id
            --所有的操作要在Enums.AuctionFilterType.all 时候生效
            --if self._selectedFilterType == Enums.AuctionFilterType.all then
                executeFunc(self._onOperate, "priceFilter",self._selectedFilterPrice)
            --end
        end
        self._btnPrice:setBright(true)
    end
end

--选择类型后回调
function ClassRef:clickTypeListItem(data)
    --print(data.name..data.id)
    if cc.isAlive(self) then
        if data.id ~= self._selectedFilterType then
            self:_setFilterName(self._btnType,data.name)
            self._selectedFilterType = data.id

            --此处要处理3种情况 第一 普通模式下 只有全部类型 和 我的出售 第二 竞价模式下 会出现我的竞价 这里选择不同会发送不同的消息
            if self._selectedFilterType == Enums.AuctionFilterType.all then
                executeFunc(self._onOperate, "changeFilter")
            elseif self._selectedFilterType == Enums.AuctionFilterType.mySold then
                executeFunc(self._onOperate, "changeFilterMySell")
            elseif self._selectedFilterType == Enums.AuctionFilterType.myBid then
                executeFunc(self._onOperate, "changeFilterMyBid")
            end
        end
        self._btnType:setBright(true)
    end
end

--返回类型过滤的值
function ClassRef:getTypeFilterValue()
    return self._selectedFilterType
end

function ClassRef:_setFilterName(btn,name)
    btn:getChildByName("name"):setString(name)
end

function ClassRef:resetSelectFilter()
    --默认选中的为 全部品质 售价更低 全部类型
    self._selectedFilterGrade = Enums.AuctionFilterQuality.all
    self._selectedFilterPrice = Enums.AuctionFilterSoldPrice.lower
    self._selectedFilterType = Enums.AuctionFilterType.all

    self:_setFilterName(self._btnGrade, L(string.format("auction_quality%d",self._selectedFilterGrade)))
    self:_setFilterName(self._btnPrice, L(string.format("auction_priceFilter%d",self._selectedFilterPrice)))
    self:_setFilterName(self._btnType, L(string.format("auction_type%d",self._selectedFilterType)))
end


function ClassRef:onOperate( cb )
    self._onOperate = cb
end

--data = {showIdx = self._currentSelectTabIdx,curPageIdx = self._curPageIdx,curPageMax = self._curPageMax, productList = showData, isLastPage = isLastPage, isNotUseTotalCount = isNotUseTotalCount}
function ClassRef:refresh(data)
    if data then
        self:setVisible( true )
        self._showListType = data.showIdx -- 该界面显示的商品类型 1为普通商品 2为竞价商品
        local subMenuInfo = GD:queryAuctionshopById(self._curSelectedClassifyId)
        if self._showListType == Enums.AuctionProductType.normal then
            if tonumber(subMenuInfo.goodType) == 1 then
                self._titleText3:setString(L("text_10800044"))
            else
                self._titleText3:setString(L("text_10800020"))
            end
            self._titleText2:setString(L("text_10800021"))

        else
            self._titleText2:setString(L("text_10800023"))
            self._titleText3:setString(L("text_10800024"))
        end

        self._typeNameList = self:_getTypeFilterList(self._btnType,self._showListType)
        self:initMoneyPanel(self._showListType)
        --self._curPageNum:setString(data.curPageIdx.."/"..data.curPageMax)
        --self._curPageNum:setVisible(false)

        if data.isNotUseTotalCount and data.isLastPage then
            display.setBtnTouchEnable(self._nextBtn, false)
        else
            display.setBtnTouchEnable(self._nextBtn, data.curPageIdx < data.curPageMax)
        end

        display.setBtnTouchEnable(self._preBtn, data.curPageIdx > 1)

        self._productListnode:reloadData(data.productList, {startIndex = 1})
    end
end

function ClassRef:onOperate(cb)
    self._onOperate = cb
end

--根据配置初始化分类
function ClassRef:initClassify(data)
    --dump(data)

    local function operate(op, data)
        if op == "btnClick" then
        elseif op == "subBtnClick" then
            --dump(data)
            if self._curSelectedClassifyId ~= data.id then
                self._curSelectedClassifyId = data.id
                executeFunc(self._onOperate, "selectedTarget", data)
            end
        end
    end

    local params = {
        list = self._ui["Panel/ListView"],
        btnClass = AuctionFirstTargetRender,
        subBtnClass = AuctionSecondTargetRender,
        operate = operate,
        mustHaveTarget = true,
        onlyOpen = true,
        autoHideSecond = true,
    }
    self._classifyList = ListMenu.new(params)
    self._classifyList:refreshList( data )

end

-- 指定具体选目标
function ClassRef:setTargetSeleced( firstTarget, secodnTarget )
    firstTarget = firstTarget or 1
    secodnTarget = secodnTarget or 1
    self._classifyList:selectBtn( firstTarget, secodnTarget )
end


function ClassRef:remove()
    self._classifyList:remove()
end

--筛选显示符合当前等级的商品
function ClassRef:_showMyLvProduct()
    local isBright = self._selectedBtn:isBright() --默认未选中状态 isBright = true
    self._selectedBtn:setBright(not isBright)
    self._isOnlyShowMyLvProducts = not self._isOnlyShowMyLvProducts
    --所有的操作要在Enums.AuctionFilterType.all 时候生效
    if self._selectedFilterType == Enums.AuctionFilterType.all then
        executeFunc(self._onOperate, "changeFilterMyLv")
    end
end

--显示货币的tips
function ClassRef:_showMoneyTips()
    local coinId = 99
    if self._showListType == Enums.AuctionProductType.normal then
        coinId = tonumber(GD:getSystemPar( "auctionNormalGoodsLootType",99))
    elseif self._showListType == Enums.AuctionProductType.bid then
        local publisher = app:getInnerPublisher()
        if publisher == Enums.Publisher.tencent then
            coinId = tonumber(GD:getSystemPar( "auctionBiddingGoodsLootType_tencent",99))
        else
            coinId = tonumber(GD:getSystemPar( "auctionBiddingGoodsLootType",115))
        end
    end
    self:showPanelTips(self._ui.Panel_money,{tipsType = Enums.TipsType.daibi, itemId = coinId})
end

function ClassRef:showPanelTips(panel, param)
    local boundingBoxTemp = panel:getBoundingBox()
    local worldPosTemp = panel:getParent():convertToWorldSpace( cc.p( boundingBoxTemp.x, boundingBoxTemp.y ) )
    boundingBoxTemp.x = worldPosTemp.x
    boundingBoxTemp.y = worldPosTemp.y
    param.boundingBox = boundingBoxTemp
    app:dispatchCustomEvent("EVENT_OPEN_FLOAT", {params = param})
end

--返回当前选中的分类ID
function ClassRef:getCurSelectedClassifyId()
    return self._curSelectedClassifyId
end

--查看商品出售列表
--sub_menu 二级分类（对应auctionshop表中的ID字段
--quality 品质(默认为0，表示不过滤品质)
--bidding_price_asc 售价排序(0表示不排序，1表示价格从低到高排序，2表示从高到低排序。对于普通商品，基于售价排序；对于竞价商品，基于最高竞价排序)
--pages 页数(0：表示请求所有商品信息，单次请求上限100条;如果页数超限，返回最后一页)
--my_use_lv bool类型 过滤出符合我的使用等级的商品
function ClassRef:getFilterConditions()
    local conditionData = {}
    conditionData.sub_menu = self._curSelectedClassifyId
    conditionData.quality = self._selectedFilterGrade
    conditionData.bidding_price_asc = self._selectedFilterPrice
    conditionData.my_use_lv = self._isOnlyShowMyLvProducts
    conditionData.typeFilter = self._selectedFilterType
    return conditionData
end


function ClassRef:isOnlyShowMyLv()
    return self._isOnlyShowMyLvProducts
end

function ClassRef:getPriceFilter()
    return self._selectedFilterPrice
end

function ClassRef:resetSearchName()
    self._editText:setText("")
end

function ClassRef:setSearchName(name)
    self._editText:setText(name)
    if name and name ~= "" then
        executeFunc(self._onOperate, "searchProductByName",self._editText:getText())
    end
end

return ClassRef
